package com.alipay.sdk.abcphaima;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.CallSuper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.sdk.abcphaima.bean.AbcpPageResultData;
import com.alipay.sdk.util.LogUtil;
import com.alipay.sdk.util.TextUtil;

import java.util.HashMap;
import java.util.Map;

public class AbcpHMLoadingPage {
    private static String sessionId;
    private static String tradeNo;
    private static int count = 0;

    public static void showPage(String msg, AbcpHM.AbcpLoadingCallback callback) {
        if (!AbcpHM.getInstance().isAbcpInitSuccess()) {
            return;
        }
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("cardTag", "MOCK_NFC_TAG");
        AbcpHM.startCanteenBPaaSService(
                "canteen",
                "requestSession",
                jsonParams,
                new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        LogUtil.d("启动Loading 出参" + response);
                        if (response == null || response.getCode() == BPaaSResponse.RESULT_CODE_FAIL) {
                            // bpaas服务调用失败
                            callback.onFail("", "bpaas服务调用失败");
                        } else if (response.getResult() != null) {
                            Bundle result = response.getResult();
                            Bundle result_result = result.getBundle("result");
                            if (result_result != null) {
                                sessionId = result_result.getString("sessionId");
                                tradeNo = result_result.getString("tradeNo");
                                show(msg, callback);
                            }
                        }


//                        if (result != null) {
//                            Bundle result_result = result.getBundle("result");
//                            if (result_result != null) {
//                                sessionId = result_result.getString("sessionId");
//                                tradeNo = result_result.getString("tradeNo");
//                                // TODO 展示Loading或支付结果页
//
//                                show(msg);
//                            }
//                        }
                        //TODO 获取session信息失败

                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {

                    }
                });


    }

    /**
     * 拉起等待
     *
     * @param msg
     */
    public static void show(String msg, AbcpHM.AbcpLoadingCallback callback) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", sessionId);
        jsonObject.put("advancedConfig", createAdvancedConfig(msg).toJSONString()); // 必填，自定义结果页展示数据

        AbcpHM.startCanteenBPaaSService("payResult", "showCardPayLoadingPage",
                jsonObject, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {
                        System.out.println("成功响应");
                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {
                        JSONObject jsonObject1 = JSONObject.parseObject(s1);
                        if ("CLOSE".equals(jsonObject1.getString("messageType"))) {
                            callback.onFail("", "超时");
                        } else if ("SMILE_VERIFY_RESULT".equals(jsonObject1.getString("messageType"))) {
                            JSONObject result = JSONObject.parseObject(jsonObject1.getString("messageContent"));
                            String subCode = result.getString("subCode");
                            String subMessage = result.getString("subMessage");
                            String sessionId = result.getString("sessionId");
                            String tradeNo = result.getString("tradeNo");
                            String barCode = result.getString("barCode");
                            String authCode, alipayUid = "";
                            LogUtil.d("启动刷脸 出参" + result);
                            if (subCode.equals("SCAN_BAR_CODE")) {
                                authCode = result.getString("scanCode");
                            } else {
                                alipayUid = result.getString("alipayUid");
                                authCode = result.getString("ftoken");
                            }
                            LogUtil.d("刷脸结果"
                                    + "\nsessionId = " + sessionId
                                    + "\ntradeNo = " + tradeNo
                                    + "\nauthCode = " + authCode
                                    + "\nbarCode = " + barCode
                                    + "\nalipayUid = " + alipayUid);
                        }
                        callback.onEvent(sessionId);
                    }
                });
        callback.onSuccess(tradeNo, sessionId, "");

//        getHandler().postDelayed(mMockQrCodePayResultJob, 3000L);
    }

    private static final Runnable mMockQrCodePayResultJob = () -> {
        System.out.println("成功显示");
        close();
    };

    private static JSONObject createAdvancedConfig(String msg) {
        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");// 表示启用新版本结果页，必须
        JSONObject OuterSummary = new JSONObject();
        OuterSummary.put("title", msg);// 结果页标题，必须
        advancedConfig.put("OuterSummary", OuterSummary);
        return advancedConfig;
    }


    private static void close() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", sessionId);
        jsonObject.put("tradeNo", tradeNo);
        jsonObject.put("resultTimeOut", 1);
        jsonObject.put("advancedConfig", customResultPageInfo().toJSONString()); // 必填，自定义结果页展示数据
        AbcpHM.startCanteenBPaaSService("payResult", "showScanCardOfflinePayResult",
                jsonObject, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse bPaaSResponse) {

                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {

                    }
                });


    }


    private static Handler mHandler;

    private static Handler getHandler() {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        return mHandler;
    }

    private static JSONObject customResultPageInfo() {
        JSONObject advancedConfigJson = new JSONObject();
        JSONObject outerSummaryJson = new JSONObject();
        outerSummaryJson.put("title", "网络请求错误");                                 // 结果页标题
        outerSummaryJson.put("subTitle", "请检查网络");                      // 结果页副标题
        outerSummaryJson.put("actualAmount", "0");                               // 实际支付金额
        outerSummaryJson.put("enablePaymentVoice", false);                            // 是否语音播报支付结果：true=播报； false=不播报
        advancedConfigJson.put("OuterSummary", outerSummaryJson);     // 结果页交易概要
        advancedConfigJson.put("version", "2.0");                                    // 必须包含此字段且值为2.0
        return advancedConfigJson;
    }


}
